<%@page import="com.sdry.entity.base.Staff"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<jsp:include page="../../common.jsp"></jsp:include>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>合同协议信息</title>
    <%
        String path = request.getContextPath();
    %>
    <%--ueditorUE--%>
    <script type="text/javascript" charset="utf-8" src="<%=path %>/statics/ueditor/ueditor.config.js"></script>
    <script type="text/javascript" charset="utf-8" src="<%=path %>/statics/ueditor/ueditor.all.min.js"> </script>
    <script type="text/javascript" charset="utf-8" src="<%=path %>/statics/ueditor/lang/zh-cn/zh-cn.js"></script>
<%
    Staff staff = (Staff)session.getAttribute("staff");
    String dname = null;
    if(staff != null){
    	if(staff.getDepartment() != null){
	      dname = staff.getDepartment().getDname();
    	}
    }
  %>
    <style>
        /*初始化编辑器边框*/
        .edui-default .edui-editor {
            border: 0px solid #d4d4d4;
        }
        /*初始化编辑器高度,默认320*/
        #edui1_iframeholder{
            height: 80vh !important
        }
    </style>
    
    <style type="text/css">
    	.d1	{
    		display: none;
    	}
    	#tb_table th{
    		font-size:20px
    	}
    </style>
    <script type="text/javascript">
        //ueditorUE 初始化文本编辑器
        //var ue = UE.getEditor('content');
        var ue = UE.getEditor('html',{
            //这里可以选择自己需要的工具按钮名称,此处仅选择如下五个
            toolbars:[],
            //关闭字数统计
            wordCount:false,
            //默认的编辑区域高度
            initialFrameWidth:null,
            //initialFrameHeight:null,  //初始化编辑器高度,默认320
            //更多其他参数，请参考ueditor.config.js中的配置项
        });
        //ueditorUE 去掉本地保存成功的提示框！
        ue.ready(function () {
            $(".edui-editor-messageholder.edui-default").css({ "visibility": "hidden" });
            ue.setDisabled();
        });
    </script>
    <script type="text/javascript">
        $(function () {
        	$("#exampleModal1").on('hidden.bs.modal',function(){
        		window.location.reload();
        	})
            //1.初始化Table
            var oTable = new TableInit();
            oTable.Init();

            //2.初始化Button的点击事件
            var oButtonInit = new ButtonInit();
            oButtonInit.Init();
            //初始化提示框的位置：top-center，bottom-left，bottom-right
            toastr.options.positionClass = 'toast-top-center';
            
            
            var res='';
            var count = 0;
            var value = '';
            
            //重置 流程定义（置空）
            $("#again").on("click",function(){
           	$("#appendDept").val("");
         		$("#dept").empty();
         		$("#people").empty();
         		res = '';
          		count = 0;
          		value = '';
         		 $.ajax({
        	        type: 'POST',
        	        url: '${pageContext.request.contextPath}/approval/queryAllDept.do',
        	        dataType: 'json',
        	        async:false,
        	        success: function (data){
        	            for (var i = 0; i < data.length; i++) {
        	                $("#dept").append("<option id='"+ data[i].did +"' value='"+ data[i].dname +"'>"+ data[i].dname +"</option>");
        	            }
        	            $("#dept").removeAttr("disabled");
        	            $("#people").removeAttr("disabled");
        	        }
        		})
            });
           
           //选中人
            $("#people").on("dblclick",function(){
            	var dname = $("#dept option:selected")[0].value;
       	  		$("#types").val("1");
	            	if($("#appendDept").val() == '') {
	            		res = '';
	            		count = 0;
	            		value = '';
	            	}
	            	
	            	if(dname == '财务部'){
						value = $(this).val()+"[财务部]";
	            	}else {
						value = $(this).val();
	            	}
	            	
	            	if (dname == '财务部' && $("#appendDept").val() == '') {
   	            		toastr.warning('第一个不能选择财务部！');
   					} else {
   						if (dname == '财务部') {
   							$("#people").attr("disabled", true);
   						}
   						
   						count ++;
   		            	if (count == 1) {
   		            		res += value;
   			            	$("#appendDept").val(res);
   			            	$("#people option:selected").attr("disabled", true);
   						} else {
   							res += '—>'+value;
   			            	$("#appendDept").val(res);
   			            	$("#people option:selected").attr("disabled", true);
   						}
   		            	if (count == 4) {
   		            		$("#people").attr("disabled", true);
   						}
   					}
	    		});
           
           //页面加载查询所有部门
   		$.ajax({
   	        type: 'POST',
   	        url: '${pageContext.request.contextPath}/approval/queryAllDept.do',
   	        dataType: 'json',
   	        success: function (data){
   	            for (var i = 0; i < data.length; i++) {
   	                $("#dept").append("<option id='"+ data[i].did +"' value='"+ data[i].dname +"'>"+ data[i].dname +"</option>");
   	            }
   	            
   	            $("#dept").on("dblclick",function(){
   	            	
   	            	if($("#types").val() == '1') {
   	            		toastr.warning('请指定人！');
   	            		return;
   	            	}
   	            	
   	            	$("#people").attr("disabled", true);
   	            	if($("#appendDept").val() == '') {
   	            		res = '';
   	            		count = 0;
   	            		value = '';
   	            	}
   	            	 
   	            	if ($(this).val() == '财务部' && $("#appendDept").val() == '') {
   	            		toastr.warning('第一个不能选择财务部！');
   					} else {
   						if ($(this).val() == '财务部') {
   							$("#dept").attr("disabled", true);
   						}
   						var did = $("#dept option:selected")[0].id;
   						value = $(this).val();
   		            	$.ajax({
   		        	        type: 'POST',
   		        	        url: '${pageContext.request.contextPath}/approval/findStaffCountByDid.do?did='+did,
   		        	        dataType: 'json',
   		        	        success: function (data){
   		        	        	if (data == 1) {
   		        	        		count ++;
   		    		            	if (count == 1) {
   		    		            		res += value;
   		    			            	$("#appendDept").val(res);
   		    			            	$("#dept option:selected").attr("disabled", true);
   		    						} else {
   		    							res += '—>'+value;
   		    			            	$("#appendDept").val(res);
   		    			            	$("#dept option:selected").attr("disabled", true);
   		    						}
   		    		            	if (count == 4) {
   		    		            		$("#dept").attr("disabled", true);
   		    						}
   								} else {
   									toastr.warning('该部门没有员工！');
   								}
   		        	        }
   		            	});
   					}
   	    		})
   	    		
   	    		 $("#dept").on("click",function(){
    	            	$("#people").empty();
    	            	var did = $("#dept option:selected")[0].id;
    	            	$.ajax({
    	        	        type: 'POST',
    	        	        url: '${pageContext.request.contextPath}/approval/queryPeopleByDept.do',
    	        	        dataType: 'json',
    	        	        data: {"did":did},
    	        	        success: function (data){
    	        	            for (var i = 0; i < data.length; i++) {
    	        	                $("#people").append("<option id='"+ data[i].staid +"' value='"+ data[i].sname +"'>"+ data[i].sname +"</option>");
    	        	            }
    	        	        }
    	        	    });
    	            });
   	        }
   		})
        
       });


        var TableInit = function () {
            var oTableInit = new Object();
            //初始化Table
            oTableInit.Init = function () {
                $('#tb_table').bootstrapTable({
                    url: "${pageContext.request.contextPath}/agreement/selectAgreementList.do",
                    method: 'get',                      //请求方式（*）
                    toolbar: '#toolbar',                //工具按钮用哪个容器
                    striped: true,                      //是否显示行间隔色
                    cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
                    pagination: true,                   //是否显示分页（*）
                    sortable: false,                     //是否启用排序
                    sortOrder: "asc",                   //排序方式
                    queryParams: oTableInit.queryParams,//传递参数（*）
                    sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
                    pageNumber:1,                       //初始化加载第一页，默认第一页
                    pageSize: 10,                       //每页的记录行数（*）
                    pageList: [10, 20, 30],        //可供选择的每页的行数（*）
                    strictSearch: true,
                    minimumCountColumns: 2,             //最少允许的列数
                    clickToSelect: true,                //是否启用点击选中行
                    //height: 550,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
                    uniqueId: "aid",                     //每一行的唯一标识，一般为主键列
                    detailView: false,                   //是否显示父子表
                    columns: [{
                        checkbox: true
                    }, {
                        field:'aid',
                        visible: false,
                        title:"编号",
                        align:'center'
                    },{
                        field:'client',
                        visible: false,
                        title:"类别id",
                        align:'center'
                    },{
                        field:'aname',
                        title:"文档标题",
                        align:'left', 
                        halign: 'center',
                        formatter: function(value, row, index){
                        	var xs = value; 
                        	var title = "文档类别"+"："+row.aremark5+"  "+"创建人"+"："+row.aremark4;
                        	if(value.length > 15){
                        		xs = value.substring(0,15)+"...";
                        		title = title+" 文档标题："+value
                        	}
                        	//标题（列宽不少于20个汉字，浮显 文档类别/创建人）
                            return "<span title='"+title+"'>"+xs+"</span>";  
                        }
                    },{
                        field:'aremark5',
                        title:"类别",
                        align:'left', 
                        halign: 'center',
                        //visible: false,
                    },{
                        field:'item',
                        title:"所属项目",
                        align:'left', 
                        halign: 'center',
           				formatter: function (value, row, index) {
           					var items =value.split(",");
           					if (items.length >= 5) {
           						return items[1];
           					}else{
           						return "";
           					}
           				}
                    },{
                        field:'item',
                        title:"专项基金",
                        align:'left', 
                        halign: 'center',
           				formatter: function (value, row, index) {
           					//项目名称（浮显 项目活动名称）
       						
           					var items =value.split(",");
           					if (items.length >= 5) {
	                        	var title = "活动名称"+"："+items[4];
	                            return "<span title='"+title+"'>"+items[3]+"</span>"; 
           						//return ;
           					}else{
           						return "";
           					}
           				}
                    },{
                        field:'item',
                        title:"活动名称",
                        align:'center',
                        visible: false,
           				formatter: function (value, row, index) {
           					var items =value.split(",");
           					if (items.length >= 5) {
           						return items[4];
           					}else{
           						return "";
           					}
           				}
                    },{
                        field:'html',
                        visible: false,
                        title:"内容",
                        align:'center'
                    },{
                        field:'aremark2',
                       	title : '文档状态',
                        align:'center',
                        width: '130px',
           				formatter: function (value, row, index) {
           					console.log(row)
           					if(value == null || value == ""){
           						return '未审批';
           					}else{
           						var deptLength = row.aremark10.split(",").length;
        						if (row.aremark10.indexOf('财务部') != -1) {
        							if (deptLength == 2) {
        								if (value.indexOf('1') != -1) {
        									if (value == 'b1') {
        										return '审批通过(已结算)';
        									} else {
        										return '审批通过';
        									}
        								}
        							}
        							if (deptLength == 3) {
        								if (value.indexOf('1') != -1) {
        									if (value == 'c1') {
        										return '审批通过(已结算)';
        									} else if(value == 'b1') {
        										return '审批通过';
        									}else {
        										return '审批中';
        									}
        								}
        							}
        							if (deptLength == 4) {
        								if (value.indexOf('1') != -1) {
        									if (value == 'd1') {
        										return '审批通过(已结算)';
        									} else if(value == 'c1') {
        										return '审批通过';
        									}else {
        										return '审批中';
        									}
        								}
        							}
        							if (value == '0') {
        								return '审批中';
        							} 
        							if (value.indexOf('2') != -1) {
        								return '已回退';
        							}
        						} else {
        							if (deptLength == 1) {
        								if (value.indexOf('1') != -1) {
        									return '审批通过(已结算)';
        								} 
        							}
        							if (deptLength == 2) {
        								if (value.indexOf('1') != -1) {
        									if (value == 'b1') {
        										return '审批通过(已结算)';
        									} else {
        										return '审批中';
        									}
        								}
        							}
        							if (deptLength == 3) {
        								if (value.indexOf('1') != -1) {
        									if (value == 'c1') {
        										return '审批通过(已结算)';
        									} else {
        										return '审批中';
        									}
        								}
        							}
        							if (deptLength == 4) {
        								if (value.indexOf('1') != -1) {
        									if (value == 'd1') {
        										return '审批通过(已结算)';
        									} else {
        										return '审批中';
        									}
        								}
        							}
        							if (value == '0') {
        								return '审批中';
        							} 
        							if (value.indexOf('2') != -1) {
        								return '已回退';
        							}
        						}
           					}
           					
                         }
                    },{
                        field:'createdate',
                        title:"创建日期",
                        align:'center',
                        width: '80px',
           				formatter: function (value, row, index) {
      					    var date =  new Date(value);
      					    var y = 1900+date.getYear();
      					    var m = "0"+(date.getMonth()+1);
      					    var d = "0"+date.getDate();
      					  	var xs =  y+"-"+m.substring(m.length-2,m.length)+"-"+d.substring(d.length-2,d.length);
	                      	var title = "创建人"+"："+row.aremark4;
	                      	//标题（列宽不少于20个汉字，浮显 文档类别/创建人）
                          	return "<span title='"+title+"'>"+xs+"</span>";
           				}
                    },{
                        field:'aremark7',
                        title:"归档人",
                        align:'center',
                        width:"100px",
                        visible: false,
                    },{
                        field:'aremark8',
                        title:"归档日期",
                        align:'center',
                        //width:"150px",
                        width: '80px',
           				formatter: function (value, row, index) {
           					if(value == null || value == ""){
           						return "";
           					}else{
	      					    var date =  new Date(value);
	      					    var y = 1900+date.getYear();
	      					    var m = "0"+(date.getMonth()+1);
	      					    var d = "0"+date.getDate();
	      					  	var xs =  y+"-"+m.substring(m.length-2,m.length)+"-"+d.substring(d.length-2,d.length);
		                      	var title = "归档人"+"："+row.aremark7;
		                      	//标题（列宽不少于20个汉字，浮显 文档类别/创建人）
	                          	return "<span title='"+title+"'>"+xs+"</span>";
           					}
           				}
                    },{
                        field:'aremark6',
                        title:"归档",
                        align:'center',
                        width:"80px",
                        visible: false,
                        formatter : function(cell, row, index) {
                        	if(cell == 0){
                        		//判断审批状态   0通过  1回退  2通过已结算  -1未审批  -2审批中 
                                var spStare = shenpiStare(row);
                        		if(spStare == "2"){
		                            cell ='<button type="button" class="btn btn-primary" onclick="filedAgreement('+row.aid+')">归档</button>';
                        		}else{
                        			cell = "请审批"
                        		}
                        	}else{
                        		cell = "已归档"
                        	}
                            return cell;
                        },
                    },{
                        field:'aid',
                        title:"预览",
                        align:'center',
                        width:"30px",
                        formatter : function(cell, row, index) {
                            cell ='<button type="button" id="btn_preview" class="btn btn-primary" style="padding: 0px;margin: 0px;" onclick="preview('+row.aid+')">预览</button>';
                            return cell;
                        },
                    },],
                });
            };

            //得到查询的参数
            oTableInit.queryParams = function (params) {
                var temp = {   //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
                    page: params.offset/params.limit+1,   //页面大小
                    rows: params.limit,  //页码
                    aname:$.trim($('#anameTJ').val()),
                    client:$.trim($('#clientTJ').val()),
                    aremark9:'${aremark9}',
                };
                return temp;
            };
            return oTableInit;
        };


        var ButtonInit = function () {
            var oInit = new Object();
            var postdata = {};

            oInit.Init = function () {
                //初始化页面上面的按钮事件
            };

            return oInit;
        };

        function preview(tid) {
            $.ajax({
                url: '/agreement/selectAgreementById.do' ,
                type: 'post',
                async:false,
                dataType:'json',
                data:"id="+tid,
                success: function (data) {
                    if(data.html == null){
                        toastr.warning('该内容为空');
                    }else{
                        ue.setContent(data.html);
                        $('#exampleModal').modal(open);
                    }
                },
            });
        }
        
        function filedAgreement(aid) {
   	       if ("<%=dname%>" != "公益事业部") {
   	       		toastr.warning('只有公益事业部可以进行归档操作');
   	         	return;
   	       }
        	//询问框
    		Ewin.confirm({ message: "确认要归档选择的数据吗？" }).on(function (e) {
    	       if (!e) {
    	         return;
    	       }
	        	$.ajax({
	                url: '/agreement/filedAgreement.do' ,
	                type: 'post',
	                async:false,
	                dataType:'json',
	                data:"aid="+aid,
	                success: function (data) {
	                    if(data == 0){
	                        toastr.warning('归档失败');
	                    }else{
	                        toastr.success('归档成功');
	                        setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
	    						$('#tb_table').bootstrapTable('refresh');
	    						refresh()
	    					},1000);
	                    }
	                },
	            });
    		}); 
        }

        //判断本页是否数据是否为空，如果为空跳转至第一页
        function refresh(){
            setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
                var row=$('#tb_table').bootstrapTable('getData');
                if(row.length == 0){
                    $("#tb_table").bootstrapTable("refreshOptions",{pageNumber:1});
                }
            },1000);
        }
        //删除
        function doDelete() {
            var row = $.map($("#tb_table").bootstrapTable('getSelections'),function(row){
                return row ;
            });
            if (row.length == 0) {
                toastr.warning('请至少选择一条数据!');
            }else{
                var ids = "";
                var names = "";
                var isshp = 0;
                for(var i = 0;i < row.length;i++){
                	//判断审批状态   0通过  1回退  2通过已结算  -1未审批  -2审批中 
                    var spStare = shenpiStare(row[i]);
                	if(spStare == "-1"){
                	//if(row[i].aremark2 == null || row[i].aremark2 == ""){
	                	if(i == 0 || i == "0"){
	                        ids += row[i].aid;
	                    }else{
	                        ids += "," + row[i].aid;
	                    }
                	}else{
                		isshp = 1;
                		break;
                	}
                }
                
                if(isshp == 1 ){
                	toastr.warning('只删除未审批过的信息!');
                }else{
                	
	                //询问框
	                Ewin.confirm({ message: "确认要删除选择的数据吗？" }).on(function (e) {
	                    if (!e) {
	                        return;
	                    }
	                    var url = "${pageContext.request.contextPath }/agreement/deleteAgreement.do";
	                    $.post(url, "ids="+ids, function(data) {
	                        if (data >= 1) {
	                            toastr.success('删除成功');
	                            setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
	                                $('#tb_table').bootstrapTable('refresh');
	                                refresh();
	                            },1000);
	                        } else {
	                            toastr.error('删除失败');
	                            setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
	                                $('#tb_table').bootstrapTable('refresh');
	                                refresh();
	                            },1000);
	                        }
	                    });
	                });
                }

            }
        }
        //打开添加框
        function doAdd() {
            window.location.href="${pageContext.request.contextPath}/agreement/pageToAgreementXq.do";
        }

        //打开修改框
        function doView() {
            //取表格的选中行数据
            var rows = $("#tb_table").bootstrapTable('getSelections');
            if (rows.length == 1) {
            	var row = rows[0];
            	//判断审批状态   0通过  1回退  2通过已结算  -1未审批  -2审批中 
                var spStare = shenpiStare(row);
            	if(spStare == "-1" || spStare == "1"){
                	window.location.href="${pageContext.request.contextPath}/agreement/pageToAgreementXq.do?id="+row.aid;
            	}else{
            		toastr.warning('只修改未审批过或回退的信息!');
            	}
            }else{
                toastr.warning('请选择一条数据!');
            }
        }
      //判断审批状态   0通过  1回退  2通过已结算  -1未审批  -2审批中 
        function shenpiStare(row) {
        	var stare = -1;
        	var value = row.aremark2
        	if(value == null || value == ""){
        		stare = -1;
        	}else{
        		var deptLength = row.aremark10.split(",").length;
        		if (row.aremark10.indexOf('财务部') != -1) {
        			if (deptLength == 2) {
        				if (value.indexOf('1') != -1) {
        					if (value == 'b1') {
        						//return '审批通过(已结算)';
        						stare = 2;
        					} else {
        						//return '审批通过';
        						stare = 0;
        					} 
        				}
        			}
        			if (deptLength == 3) {
        				if (value.indexOf('1') != -1) {
        					 if (value == 'c1') {
        						//return '审批通过(已结算)';
        						 stare = 2;
        					} else {
        						//return '审批通过';
        						stare = 0;
        					} 
        				}
        			}
        			if (deptLength == 4) {
        				if (value.indexOf('1') != -1) {
        					if (value == 'd1') {
        						//return '审批通过(已结算)';
        						stare = 2;
        					} else {
        						//return '审批通过';
        						stare = 0;
        					}
        				}
        			}
        			if (value == '0') {
        				//return '审批中';
        				stare = -2;
        			} 
        			if (value.indexOf('2') != -1) {
        				//return '已回退';
        				stare = 1;
        			}
        		} else {
        			if (deptLength == 1) {
        				if (value.indexOf('1') != -1) {
        					//return '审批通过(已结算)';
        					stare = 2;
        				} 
        			}
        			if (deptLength == 2) {
        				if (value.indexOf('1') != -1) {
        					if (value == 'b1') {
        						//return '审批通过(已结算)';
        						stare = 2;
        					} else {
        						//return '审批中';
        						stare = -2;
        					}
        				}
        			}
        			if (deptLength == 3) {
        				if (value.indexOf('1') != -1) {
        					if (value == 'c1') {
        						//return '审批通过(已结算)';
        						stare = 2;
        					} else {
        						//return '审批中';
        						stare = -2;
        					}
        				}
        			}
        			if (deptLength == 4) {
        				if (value.indexOf('1') != -1) {
        					if (value == 'd1') {
        						//return '审批通过(已结算)';
        						stare = 2;
        					} else {
        						//return '审批中';
        						stare = -2;
        					}
        				}
        			}
        			if (value == '0') {
        				//return '审批中';
        				stare = -2;
        			} 
        			if (value.indexOf('2') != -1) {
        				//return '已回退';
        				stare = 1;
        			}
        		}
        	}
        	return stare;
        }
        //打开修改框
        function guidang() {
            //取表格的选中行数据
            var rows = $("#tb_table").bootstrapTable('getSelections');
            if (rows.length == 1) {
            	var row = rows[0];
            	var cell = row.aremark6
               	if(cell == 0){
               		//判断审批状态   0通过  1回退  2通过已结算  -1未审批  -2审批中 
                    var spStare = shenpiStare(row);
               		if(spStare == 2){
                           filedAgreement(row.aid);
               		}else{
               			toastr.warning('该文档未结算，不能归档!');
               		}
               	}else{
               		toastr.warning('该文档已归档!');
               	}
            }else{
                toastr.warning('请选择一条数据!');
            }
        }
        //刷新表格
        function seach() {
            $("#tb_table").bootstrapTable("refreshOptions",{pageNumber:1});
        }
        
        //打开编辑流程的模态框
        function doSub() {
        	//清空呈批件id内容
        	$("#idCpj").val(""); 
        	 var a= $('#tb_table').bootstrapTable('getSelections'); 
             
             var ids = "";
             for(var i = 0;i<a.length;i++) {
            	//判断审批状态   0通过  1回退  2通过已结算  -1未审批  -2审批中 
                 var spStare = shenpiStare(a[i]);
             		if(spStare == "-2" || spStare == "0" || spStare == "2"){
            		 toastr.warning('已提交审批，请勿重复操作！');
                	 return false;
            	 }
             }
             for(var i = 0;i<a.length;i++) {
            	 if(i != a.length-1) {
            	 	ids +=a[i].aid+",";
            	 }else {
            	 	ids +=a[i].aid;
            	 }
             }

             if(a == null || a == "" || a == undefined){
            	 toastr.warning('请至少选择一条记录！');
            	 return false;
             }
             
             //判断呈批件审批
             if(a.length > 1){
            	 var f = 0;
            	 var anames = "";
            	 for(var i = 0;i<a.length;i++) {
                	 if(a[i].aremark5 == "呈批件"){
                		 f++;
			            $("#idCpj").val(a[i].aid); 
			            $("#aname").val(a[i].aremark5);
                	 }else {
                		 if(i != a.length-1) {
                			 anames +=a[i].aremark5+",";
                       	 	
                       	 }else {
                       		anames +=a[i].aremark5;
                       	 }
                		 
                		 $("#aname").val(anames);
                	 }
                 }
            	 
            	 if(f != 1){
            		 toastr.warning('呈批件审批必须选择有且只有一个对应的呈批件文件！');
	            	 return false;
            	 }
             }else if(a.length == 1){
            	 if(a[0].aremark5 == "呈批件"){
            		 toastr.warning('单个呈批件文件不能审批！');
	            	 return false; 
            	 }else {
            		 $("#aname").val(a[0].aremark5);
            	 }
             }
             
            $("#ids").val(ids); 
            $("#appendDept").val(""); 
            
            $('#exampleModal1').modal(open);
        }
        
      //是否执行保存操作标识
    	var addFlg = false;
      	//提交申请
        function submitApproval() {
      		//获取审批人
      		var dept = $("#appendDept").val();
      		if(dept == "" || dept == undefined || dept == null) {
      			toastr.warning('请选择审批部门 或 审批人！');
      			return false;
      		}
      		
            if (addFlg ==true) {
                return false;
            }
            addFlg  =  true; 
            var a= $('#tb_table').bootstrapTable('getSelections'); 
            
            var ids = "";
            for(var i = 0;i<a.length;i++) {
           	 if(i != a.length-1) {
           	 	ids +=a[i].aid+",";
           	 	
           	 }else {
           	 	ids +=a[i].aid;
           	 }
            }
            var form = new FormData(document.getElementById("fm"));
            // 添加审批人顺序
    		$.ajax({
    			type : "post",
    			url : "${pageContext.request.contextPath}/approval/insertDept.do",
    			//data : {"aname":$("#aname").val(), "appendDept":$("#appendDept").val()},
    			data : form,
				processData:false,
           		contentType:false,
                async:false,
    			success : function(data) {
    				if(data > 0){
    					 $.ajax({
					            url: "${pageContext.request.contextPath}/agreement/editAremark.do" ,
					            type: 'post',
					            data:{"aremark1":ids,"aremark":data},
					            async:false,
					            success: function (data1) {
					                if (data1 == 1) {
										addFlg = false;
					                	toastr.success('提交申请成功！');
					                	//呈批件审批时给呈批件内容中添加信息
					                	var idCpj = $("#idCpj").val();
					                	if(idCpj != "" && idCpj != null && idCpj != undefined ) {
					                		addCpj(dept,idCpj);
					                	}
					                	 setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
					                		 	$('#exampleModal').modal('hide');
												window.location.reload();
				                            },1000);
					                } else {
					                    addFlg  =  false
					                    toastr.error('提交申请失败！');
					                }
					            },
					        });
    					
    				} else {
    					addFlg  =  false
    					toastr.warning('提交申请出现错误！');
    				}
    			},
    			error : function () {
    				addFlg  =  false
    				toastr.error('提交申请失败！');
    			}
    		});
        }
      //根据审批部门+id修改呈批件内容
        function addCpj(dept,aid) {
        	var jg = "—>"
        	var arr = dept.split(jg)
        	var html = "";
        	$.ajax({
                url: '/agreement/selectAgreementById.do' ,
                type: 'post',
                async:false,
                dataType:'json',
                data:"id="+aid,
                success: function (data) {
                    if(data.html == null){
                        toastr.warning('该内容为空');
                    }else{
                    	html = data.html;
                    }
                },
            });
        	
        	var arr1 = new Array();
			for(var i = 0;i<arr.length;i++) {
				if(arr[i] != "财务部"){
					arr1.push(arr[i])
				}
			}
			
        	//把审批部门添加入呈批件内容中
        	html = tableGl(html,"table",arr1);
        	//修改内容
        	updateCPJ(html,aid)
        }
      	//根据id提交修改内容
        function updateCPJ(html,aid) {
	        $.ajax({
	            url: "${pageContext.request.contextPath}/agreement/editHtml.do" ,
	            type: 'post',
	            data:{"aid":aid,"html":html},
	            async:false,
	            success: function (data1) {
	                if (data1 == 1) {
	                	 //toastr.success('成功')
	                } else {
	                	//toastr.error('失败')
	                }
	            },
	        });
        }
      	//把审批部门添加入呈批件内容中
        function tableGl(data,s,arr) {
            //返回数据
            var dept = "^";
            var html = "";
            //标签头
            var tableq = "<"+s
    		//标签尾
            var tableh = "</"+s+">"
            //标签头分组
            var strks = data.split(tableq);
            //标签尾分组
            var strjs = data.split(tableh);

            for (var i=0;i<strks.length;i++) {
                if(i == 0){
                    html = html + strks[i];
                }else {
                	//获取相同值（table内容）
                    var ss = getMaxStr(strks[i], strjs[i-1].split(tableq)[1])
                    var qianHou = strks[i].split(ss);
					var darr = ss.split(dept)
					//头：darr[0]
					//中间行：darr[1](顶有线) != darr[2](顶无线)
					//尾：darr[3]
					var zjh = darr[1];
                    if (arr.length == 1) {
                    	var shh = darr[1].split("</tr>")
                    	var mhh = darr[3].split("</tr>")
                    	var m = "";
                    	for (var i=1;i<mhh.length;i++) {
                    		m = m + "</tr>" + mhh[i]
                    	}
						ss = darr[0] + arr[0] + shh[0]+m;
					}else if(arr.length >= 2){
						ss = darr[0] + arr[0] 
						for(var i = 1;i<arr.length;i++) {
							ss = ss + zjh + arr[i] 
	                	}
						ss = ss +darr[3];
					}
    				html = html + tableq + qianHou[0]+ss+ tableh+ qianHou[1];
                }
            }
            return html;
        }
     	 //获取俩字符中相同字段
    	function getMaxStr(str1,str2){
            var max = str1.length > str2.length ? str1 : str2;
            var min = (max == str1 ? str2 : str1);
            for(var i = 0; i < min.length; i++){
                for(var x = 0, y = min.length - i;y != min.length + 1;x++,y++){
                    //y表示所取字符串的长度
                    var newStr = min.substring(x,y);
                    //判断max中是否包含newStr
                    if(max.indexOf(newStr) != -1){
                        return newStr;
                    }
                }
            }
            return -1;
        }
    </script>
    <style type="text/css">
    	.panel{
    		margin-bottom: 0px;
    	}
    	.panel-body{
    		padding: 5px;
    	}
    	.form-group{
    		margin: 0px;
    	}
    </style>
</head>
<body>
<div class="panel-body" style="padding-bottom:0px;">
    <div class="panel panel-default">
        <!-- <div class="panel-heading">查询条件</div> -->
        <div class="panel-body">
            <form id="formSearch" class="form-horizontal">
                <div class="form-group">
                    <label class="control-label col-sm-1" for="anameTJ">文档标题</label>
                    <div class="col-sm-2">
                        <input type="text" class="form-control" id="anameTJ">
                    </div>
                    <label class="control-label col-sm-1" for="clientTJ">文档类别</label>
                    <div class="col-sm-2">
                        <!-- <input type="text" class="form-control" id="clientTJ"> -->
                        <select id="clientTJ" name="clientTJ" class="form-control selectpicker" >
							<option value="">所有类别</option>
			        	</select>
			        	<script type="text/javascript">
			                $(function(){
			                    $.ajax({
					                type: "post",
					                url: "${pageContext.request.contextPath }/type/selectAll.do",
					                dataType: 'JSON',
					                async: false,
					                success: function (data) {
					                      //设置下拉列表中的值的属性
					                      for ( var i = 0; i < data.length; i++) {
					                    	  	if (data[i].jid != $.trim($('#pid').val())) {
							                        //增加下拉列表。
							                        $("#clientTJ").append("<option value='"+data[i].id+"'>"+data[i].tname+"</option>");
												}
										 }
					                    //必须执行，否则数据新增失败
					                     $('#clientTJ').selectpicker('refresh'); 
					                }
					            });
			                });
			        	</script>
                    </div>
                    <div class="col-sm-6">
                        <button type="button" id="btn_query" class="btn btn-primary" onclick="seach()">查询</button>
                        &nbsp;&nbsp;
                        <button id="btn_add" type="button" class="btn btn-default" onclick="doAdd()">
				            <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增
				        </button>
				        <button id="btn_edit" type="button" class="btn btn-default" onclick="doView()">
				            <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>修改
				        </button> 
				       <button id="btn_delete" type="button" class="btn btn-default" onclick="doDelete()">
				            <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除
				        </button> 
				       <button id="btn_delete" type="button" class="btn btn-default" onclick="doSub()">
				            <span class="glyphicon glyphicon-ok" aria-hidden="true"></span>提交审批
				        </button>
				       <button id="btn_delete" type="button" class="btn btn-default" onclick="guidang()">
				            <span class="glyphicon glyphicon-ok" aria-hidden="true"></span>归档
				        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>
    <table id="tb_table"></table>
</div>

<div class="modal fade bs-example-modal-lg" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close closefm" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="exampleModalLabel">
                    <span style="font-size:13px">预览</span>&nbsp;&nbsp;&nbsp;&nbsp;
	                <button type="button" class="btn btn-default" onclick="dy()">
	                    <span class="glyphicon glyphicon-print" aria-hidden="true"></span>
	                </button>
                </h4>
                <script type="text/javascript">
                    function dy() {
                    	var css="<style>"
                            +"table {border-collapse: collapse;" +
                                "border:1px #ddd solid;" +
                           "}"
                           +"table tr td {" +
                                "border:1px #ddd solid;" +
                           "}"
                            +"</style>";
                        var printHtml = css + ue.getContent();
                    	printpage(printHtml)
                    }
                   
                    function printpage(printHtml){    
                    	var wind = window.open("",'newwindow', 'top=100, left=100, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=n o, status=no');
                    	wind.document.body.innerHTML = printHtml;
                    	wind.print();
                    	return false; 
                    }
                </script>

            </div>
            <div class="modal-body" >
                <textarea id="html" name="html"></textarea>
            </div>
        </div>
    </div>
</div>


  <div class="modal fade" id="exampleModal1" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
   		<div class="modal-dialog" role="document">
    		<div class="modal-content" style="width: 500px;height: 400px;">
      			<div class="modal-header">
        			<button type="button" class="close closefm" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        			<h4 class="modal-title" id="exampleModalLabel">
        				<span id="bt" style="font-size:13px">请编辑审批流程</span>
        			</h4>
      			</div>
      			<div class="modal-body">
	        		<form id="fm" class="form-horizontal">
	        			<!-- 保存呈批件的id -->
	        			<input type="hidden" id="idCpj">
	        			
	        			<input type="hidden" id="ids">
	        			<input type="hidden" id="aname" name="aname">
	        			 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
						<select name="dept" id="dept" multiple="multiple" style="text-align:center; width: 150px; height:200px">
	                    </select>
	                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
						<select name="dept" id="people" multiple="multiple" style="text-align:center; width: 150px; height:200px">
	                    </select>
	                    <br>
	                     &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
						<input type="text" id="appendDept" name="appendDept" readonly="readonly" style="margin-top: 20px;text-align:center; width: 300px">
						<div class="d1">
							<input type="file" id="attachment" name="attachment" style="margin-left: 200px" accept=".doc,.docx">
						</div>
						<input type="hidden" id="types" name="types">
	          			 <div class="modal-footer">
                          	<button type="button"  class="btn btn-primary" onclick="submitApproval()">确认提交</button>
					        <button type="button"  class="btn  btn-warning"  id="again">重置</button>
                          	<button type="button" class="btn btn-default closefm" data-dismiss="modal" >关闭</button>
                        </div>
	        		</form>
	      		</div>
    		</div>
  		</div>
	</div>
</body>
</html>